'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    // 获取请求参数
    const { id } = event;
    const { OPENID } = context;
    
    // 验证请求参数
    if (!id) {
      return {
        code: 400,
        message: '分类ID不能为空'
      };
    }
    
    // 验证管理员权限
    const adminInfo = await db.collection('admin_users')
      .where({
        openid: OPENID,
        is_active: true
      })
      .field({
        _id: 1,
        username: 1,
        role: 1
      })
      .get();
    
    if (adminInfo.data.length === 0) {
      return {
        code: 403,
        message: '您没有管理员权限'
      };
    }
    
    // 查询分类详情
    const categoryInfo = await db.collection('categories')
      .doc(id)
      .get();
    
    if (categoryInfo.data) {
      // 统计该分类下的壁纸数量
      const countResult = await db.collection('wallpapers')
        .where({
          categoryId: id
        })
        .count();
      
      const result = {
        ...categoryInfo.data,
        wallpaperCount: countResult.total
      };
      
      // 记录操作日志
      await db.collection('admin_logs').add({
        admin_id: adminInfo.data[0]._id,
        admin_name: adminInfo.data[0].username,
        action: 'get_category_detail',
        target_id: id,
        target_name: result.name,
        create_time: Date.now()
      });
      
      return {
        code: 0,
        message: '获取分类详情成功',
        data: result
      };
    } else {
      return {
        code: 404,
        message: '分类不存在'
      };
    }
  } catch (error) {
    console.error('获取分类详情失败:', error);
    return {
      code: 500,
      message: '获取分类详情失败，请稍后重试',
      error: error.message
    };
  }
};